//
//  ArriveViewController.m
//  FMJY
//
//  Created by 艾玩科技 on 17/3/22.
//  Copyright © 2017年 随心. All rights reserved.
//

#import "ArriveViewController.h"
#import "PhotoView.h"
#import "MainViewController.h"
#import "LogInViewController.h"
#import "OrderViewController.h"

@interface ArriveViewController ()
{
   
    //我的位置的经纬度
    NSString *lng;
    NSString *lat;
    NSString *loginToken;
    
    PhotoView *photoView;
    
    UIButton *overBtn;
    //进度条
    UIProgressView *progressV;
    //正在上传lable提示
    UILabel *upImagesLabel;
    
    UIActivityIndicatorView *indicator;
}
@end

@implementation ArriveViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"上传照片";
    //起点 传入的是原始的经纬度坐标，若使用的是百度地图坐标，可以使用BNTools类进行坐标转化
    CLLocation *myLocation = [BNCoreServices_Location getLastLocation];
    lng = [NSString stringWithFormat:@"%f",myLocation.coordinate.longitude];
    lat = [NSString stringWithFormat:@"%f",myLocation.coordinate.latitude];
        
    loginToken = GetUserLoginToken;
//    [NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"user_loginToken"]];
    UILabel *alertLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 64, KScreenWidth, 44)];
    alertLabel.text = @"至少上传X张现场照片，必须包含车主签字照片";
    alertLabel.backgroundColor = [UIColor colorWithRed:0.910 green:0.910 blue:0.910 alpha:1.00];
    alertLabel.textColor = [UIColor lightGrayColor];
    alertLabel.textAlignment = NSTextAlignmentCenter;
    alertLabel.font = [UIFont systemFontOfSize:15];
    [self.view addSubview:alertLabel];
   
    
    photoView = [[PhotoView alloc] initWithFrame:CGRectMake(0, alertLabel.bottom, KScreenWidth, KScreenHeight - 70 -alertLabel.height )];
    [self.view addSubview:photoView];
    //正在上传lable提示
    upImagesLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, KScreenHeight - 100, KScreenWidth, 20)];
    
    upImagesLabel.hidden = YES;
    upImagesLabel.font = [UIFont systemFontOfSize:14];
    upImagesLabel.textAlignment = NSTextAlignmentCenter;
    upImagesLabel.backgroundColor = [UIColor clearColor];
    upImagesLabel.textColor = [UIColor lightGrayColor];
    [self.view addSubview:upImagesLabel];
    //进度条
    progressV = [[UIProgressView alloc] initWithFrame:CGRectMake(50, KScreenHeight - 80, KScreenWidth - 50 *2, 1)];
    progressV.hidden = YES;
    [self.view addSubview:progressV];
    //拍摄完成
    overBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    overBtn.frame = CGRectMake(27, KScreenHeight - 70, KScreenWidth - 27.f *2.0f, 50);
    [overBtn setTitle:@"拍摄完成" forState:UIControlStateNormal];
    [overBtn addTarget:self action:@selector(photoOverBtnAct:) forControlEvents:UIControlEventTouchUpInside];
    overBtn.backgroundColor = [UIColor colorWithRed:0.835 green:0.835 blue:0.835 alpha:1.00];
    overBtn.userInteractionEnabled = NO;
    overBtn.layer.cornerRadius = 4;
    overBtn.layer.masksToBounds = YES;
    [self.view addSubview:overBtn];


    //接收图片上传的进度
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setBtnTitle:) name:@"upimgsRate" object:nil];
    //上传成功的提示
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alertSucessAct:) name:@"alertSucess" object:nil];
    

}
#pragma mark --
-(void)alertSucessAct:(NSNotification *)notify
{
    progressV.hidden = YES;
    upImagesLabel.hidden = YES;
    overBtn.userInteractionEnabled = YES;
   
    overBtn.backgroundColor = [UIColor colorWithRed:0.337 green:0.678 blue:0.957 alpha:1.00];
    

}
#pragma mark --  图片上传进度的提示 --
-(void)setBtnTitle:(NSNotification *)notif
{
//    [overBtn setTitle:[NSString stringWithFormat:@"上传进度:%@%%",[notif.userInfo objectForKey:@"rate" ]] forState:UIControlStateNormal];
    upImagesLabel.text = [NSString stringWithFormat:@"正在上传%.f%%,请稍后",[[notif.userInfo objectForKey:@"rate" ] floatValue] *100];
    progressV.hidden = NO;
    upImagesLabel.hidden = NO;
    progressV.progress = [[notif.userInfo objectForKey:@"rate" ] floatValue];
    
    //图片没有上传成功时，上传完成按钮不能点击
    if (![[notif.userInfo objectForKey:@"rate" ] isEqualToString:@"1.0"]) {
    
        overBtn.backgroundColor = [UIColor colorWithRed:0.835 green:0.835 blue:0.835 alpha:1.00];
        overBtn.userInteractionEnabled = NO;

    }
    
}
#pragma mark --  风火轮 --
-(void)loadActivityView
{
    indicator = nil;
    indicator = (UIActivityIndicatorView *)[self.view viewWithTag:103];
    
    if (indicator == nil) {
        
        //初始化:
        indicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 80, 80)];
        
        indicator.tag = 103;
        
        //设置显示样式,见UIActivityIndicatorViewStyle的定义
        indicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
        
        
        //设置背景色
        indicator.backgroundColor = [UIColor lightGrayColor];
        
        //设置背景透明
        indicator.alpha = 0.5;
        
        //设置背景为圆角矩形
        indicator.layer.cornerRadius = 6;
        indicator.layer.masksToBounds = YES;
        //设置显示位置
        [indicator setCenter:CGPointMake(KScreenWidth / 2.0, KScreenHeight / 2.0)];
        

        
        [self.view addSubview:indicator];

    }
    
   
}
#pragma mark -- 拍摄完成 --
-(void)photoOverBtnAct:(UIButton *)btn
{
#pragma mark--------------------------
    if (photoView.images.count < 1) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"上传图片不得少于1张，请重新上传" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        
        [alert addAction:sure];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
#pragma mark--------------------------

    if ([self.isFitstStr isEqualToString:@"拖车已上板"]) {
        //将数组中内容拼接成字符串
        NSString *trailPicsStr = [NSString stringWithFormat:@"%@",[photoView.images componentsJoinedByString:@","]];
        //开始显示Loading动画
        [indicator startAnimating];
        //拖车上板
        [CoreWork DriverArriveWithorderNo:self.photo_orderNumberStr lng:lng lat:lat loginToken:loginToken trailPics:trailPicsStr  Block:^(id responsObject) {
            if (![responsObject isKindOfClass:[NSDictionary class]]) {
                
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"服务器开小差了，请稍后重试" preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
                
                [alert addAction:sure];
                [self presentViewController:alert animated:YES completion:nil];
                //开始显示Loading动画
                [indicator stopAnimating];
                return ;
               
            }
#pragma mark -- 当前订单状态不允许到达现场处理
                        if (([responsObject isKindOfClass:[NSDictionary class]]) && ([[responsObject objectForKey:@"status"] integerValue] == 0)) {
                            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"%@",[responsObject objectForKey:@"message"]] preferredStyle:UIAlertControllerStyleAlert];
            
                            UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
            
                            [alert addAction:sure];
                            [self presentViewController:alert animated:YES completion:nil];
                            //风火轮结束转动
                            [indicator stopAnimating];
                            return ;
                        }
            #pragma mark -- 拖车上板 ok --
                        else if (([responsObject isKindOfClass:[NSDictionary class]]) && ([[responsObject objectForKey:@"status"] integerValue] == 1))
                        {
                            //结束显示Loading动画
                            [indicator stopAnimating];
            //返回上一层界面,
            if ((self.photoDelegateA) && ([self.photoDelegateA respondsToSelector:@selector(sendtitle:)])) {
                [self.photoDelegateA sendtitle:@"订单已完成"];
            }
            
            [self.navigationController popViewControllerAnimated:YES];
                        }
            
            //异地登录
            if (([responsObject isKindOfClass:[NSDictionary class]] ) && ([[responsObject objectForKey:@"status"] integerValue ] == -3) ) {
                
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"%@", [responsObject objectForKey:@"message"]] preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
                
                [alert addAction:sure];
                [self presentViewController:alert animated:YES completion:nil];
                
                //返回到‘扫描界面’
                [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:0] animated:YES];
            }

            

            
        }];
        
    }
    
    
    ///////_____________________分割线______________________////////
    else if ([self.isFitstStr isEqualToString:@"订单已完成"])
    {
        //将数组中内容拼接成字符串
        NSString *destPicsStr = [NSString stringWithFormat:@"%@",[photoView.images componentsJoinedByString:@","]];
        //开始显示Loading动画
        [indicator startAnimating];
       //订单已完成
        [CoreWork OrderCompleteWithorderNo:self.photo_orderNumberStr lng:lng lat:lat loginToken:loginToken destPics:destPicsStr  Block:^(id responsObject) {
            
#pragma mark -- 服务器报错  --
            if (![responsObject isKindOfClass:[NSDictionary class]]) {
                
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"服务器开小差了，请稍后重试" preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
                
                [alert addAction:sure];
                [self presentViewController:alert animated:YES completion:nil];
                //开始显示Loading动画
                [indicator stopAnimating];
                return ;
                
            }
#pragma mark -- 订单状态不对 --
                        if (([responsObject isKindOfClass:[NSDictionary class]]) && ([[responsObject objectForKey:@"status"] integerValue] == 0)) {
                            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"%@",[responsObject objectForKey:@"message"]] preferredStyle:UIAlertControllerStyleAlert];
            
                            UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
            
                            [alert addAction:sure];
                            [self presentViewController:alert animated:YES completion:nil];
                            //开始显示Loading动画
                            [indicator stopAnimating];
                            return ;
                        }
            #pragma mark -- 账号在另一个地方登录，被迫退出 --
                        else if (([responsObject isKindOfClass:[NSDictionary class]]) && ([[responsObject objectForKey:@"status"] integerValue] == -3))
                        {
                            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"%@",[responsObject objectForKey:@"message"]] preferredStyle:UIAlertControllerStyleAlert];
                            
                            UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                                
                                //调用退出接口
                                [CoreWork logOutWithloginToken:loginToken Block:^(id responsObject) {
                                    //tuichudenglu
//                                    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isLogin"];
                                    
                                    [self.navigationController presentViewController:[[LogInViewController alloc] init] animated:YES completion:nil];
                                }];
                                
                            }];
                            
                            [alert addAction:sure];
                            [self presentViewController:alert animated:YES completion:nil];
                            
                            return ;
                        }
#pragma mark  -- 订单完成了 --
            else if (([responsObject isKindOfClass:[NSDictionary class]]) && ([[responsObject objectForKey:@"status"] integerValue] == 1))
            {
                //
                //开始显示Loading动画
                [indicator stopAnimating];
                [self.navigationController popToRootViewControllerAnimated:YES];
                
            }
            
        }];
        
    }
    ////___________________分割线________________________///
    else
    {
        
      
        //将数组中内容拼接成字符串
        NSString *arrivePicsStr = [NSString stringWithFormat:@"%@",[photoView.images componentsJoinedByString:@","]];
        //开始显示Loading动画
        [indicator startAnimating];
        
        [CoreWork driverArrivedWithorderNo:self.photo_orderNumberStr loginToken:loginToken lng:lng lat:lat arrivePics:arrivePicsStr Block:^(id responsObject) {
         

            
#pragma mark -- 服务器报错  --
            if (![responsObject isKindOfClass:[NSDictionary class]]) {
                
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"服务器开小差了，请稍后重试" preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
                
                [alert addAction:sure];
                [self presentViewController:alert animated:YES completion:nil];
                //开始显示Loading动画
                [indicator stopAnimating];
                return ;
                
            }
#pragma mark -- 当前订单状态不允许到达现场处理
            if (([responsObject isKindOfClass:[NSDictionary class]]) && ([[responsObject objectForKey:@"status"] integerValue] == 0)) {
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"%@",[responsObject objectForKey:@"message"]] preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
                
                [alert addAction:sure];
                [self presentViewController:alert animated:YES completion:nil];
                //开始显示Loading动画
                [indicator stopAnimating];
                return ;
            }
#pragma mark -- 司机成功到达现场 --
            else if (([responsObject isKindOfClass:[NSDictionary class]]) && ([[responsObject objectForKey:@"status"] integerValue] == 1))
            {
                
                //结束显示Loading动画
                [indicator stopAnimating];
                //1拖车，0非拖车
                if ([self.istrailStrA integerValue] == 0) {
                    
                    //非拖车
                    self.isFitstStr = @"订单已完成";
                    if ((self.photoDelegateA) && ([self.photoDelegateA respondsToSelector:@selector(sendtitle:)])) {
                        [self.photoDelegateA sendtitle:@"订单已完成"];
                    }
                    
                    
                    [self.navigationController popViewControllerAnimated:YES];
                    
                    
                    
                }
                else if ([self.istrailStrA integerValue] == 1)
                {
                    //拖车
                    self.isFitstStr = @"拖车已上板";
                    
                    if ((self.photoDelegateA) && ([self.photoDelegateA respondsToSelector:@selector(sendtitle:)])) {
                        [self.photoDelegateA sendtitle:@"拖车已上板"];
                    }
                    
                    
                    [self.navigationController popViewControllerAnimated:YES];

                }
                //返回上一层界面,
               
            }
            
            

            
        }];
        
        
    }
    
}
-(void)setIstrailStrA:(NSString *)istrailStrA
{
    _istrailStrA = istrailStrA;
    
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
    
    [self loadActivityView];
}

@end
